﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2016/5/4
 * Time: 15:01
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using SharpErp.Data.Common.Entity;
using SharpChannel.Core;
using SharpErp.Data.Common.View;

namespace SharpErp.Data.Service
{
    /// <summary>
    /// Description of SharpErpServiceImpl.
    /// </summary>
    public partial class SharpErpServiceImpl : ISharpErpService
    {
        public delegate BaseSession GetCurrentSessionDelegate();

        private GetCurrentSessionDelegate _getCurrentSession;
        public GetCurrentSessionDelegate GetCurrentSession { get { return _getCurrentSession; } set {
                _getCurrentSession = value;
                SharpErp.Data.Common.Context.SharpErpDbContext.GetCurrentStaff = delegate ()
                {
                    if (_getCurrentSession == null) return null;
                    return _getCurrentSession.Invoke()?.SessionData as CompanyStaffView;
                };
            } }

        public List<T> GetAllKvItemClass<T>(string key)
        {
            using (var context = new Common.Context.SharpErpDbContext())
            {
                var entity = context.SelectOne(context.KVEntities, p => p.Key.Equals(key));
                return entity == null ? new System.Collections.Generic.List<T>() :
                    Util.SerializerManager.GetInstance().GetJSSerializer().Deserialize<System.Collections.Generic.List<T>>(entity.Value);
            }
        }

        public string ping()
        {
            return "ping";
        }

        public void SetAllKvItemClass<T>(System.Collections.Generic.List<T> list, string key)
        {
            using (var context = new Common.Context.SharpErpDbContext())
            {
                var entity = context.SelectOne(context.KVEntities, p => p.Key.Equals(key)) ??
                             new KVEntity { CreateTime = new DateTime() };
                entity.LastModifyTime = new DateTime();
                entity.Key = key;
                entity.Value = Util.SerializerManager.GetInstance().GetJSSerializer().Serialize<System.Collections.Generic.List<T>>(list);
                if (entity.Id > 0)
                {
                    context.Update<Common.Entity.KVEntity>(context.KVEntities, entity);
                }
                else
                {
                    context.Add<Common.Entity.KVEntity>(context.KVEntities, entity);
                }

            }
        }
        public List<T> GetAllKvMaterialClass<T>(string key)
        {
            return GetAllKvItemClass<T>(key);
        }

        public void SetAllKvMaterialClass<T>(System.Collections.Generic.List<T> list, string key)
        {
            SetAllKvItemClass<T>(list, key);
        }

    }
}
